import { ReactElement, useState, useEffect, useRef } from 'react'
import { Modal, Form, Select, FormInstance, message } from 'antd'
import { updateRequest } from './ajax'
import { awaitWrap } from '@js/tool'
import Dictionary, { DictionaryItem } from '@js/dictionary'
import { WorkPerformanceSchema } from '@src/components/schema/performanceSchema'
const { Item } = Form
const { Option } = Select

// 修改操作
async function updateHandle (performanceid: string, d: { [k: string]: any }, refreshData: () => void, hide: () => void): Promise<void> {
  const h = message.loading('提交中')
  const [e] = await awaitWrap(updateRequest(performanceid, d))
  h()
  if (e === null) {
    hide()
    refreshData()
  }
}

interface Props {
  performanceid: string
  visible: boolean
  data: WorkPerformanceSchema | null
  hide: () => void
  refreshData: () => void
}

function Main ({ visible, hide, data, performanceid, refreshData }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  const [options, setOptions] = useState<DictionaryItem[]>([])
  useEffect(() => {
    const d = new Dictionary()
    d.init('考核类别')
      .then(() => {
        setOptions(d.getList('考核类别'))
      })
      .catch(e => console.error(e))
  }, [])
  useEffect(() => {
    const c = formRef.current
    if (visible && c !== null && data !== null) {
      c.setFieldsValue(data)
    } else if (!visible && c !== null) {
      c.resetFields()
    }
  }, [formRef, data, visible])
  return (
    <Modal visible={visible} title={'修改考核类别'} maskClosable={false} onCancel={hide} onOk={() => formRef.current?.submit()}>
      <Form ref={formRef} labelCol={{ flex: '88px' }} onFinish={async (d) => await updateHandle(performanceid, d, refreshData, hide)}>
        <Item noStyle name='accountid'><span /></Item>
        <Item label='考核类别' name='employee_type' rules={[{ required: true, message: '考核类别不能为空' }]}>
          <Select placeholder='请选择'>
            {options.map((li, i) => {
              return <Option key={i} value={li.value}>{li.title}</Option>
            })}
          </Select>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
